package com.tnf.bc.bground.certificate.filter;

import com.alibaba.fastjson.JSON;
import com.tnf.bc.bground.certificate.pojo.LoginUser;
import com.tnf.bc.bground.common.utils.jwtutils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * @description: //自定义的Token过滤器
 * @author: lzl
 * @create: 2022-11-18 17:44
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String toekn = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(toekn)) {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        String userId = JwtTokenUtil.getUsernameFromToken(toekn);
        String rediskey = "login_user_"+userId;
        String loginUserInfo = redisTemplate.opsForValue().get(rediskey);
        LoginUser loginUser = JSON.toJavaObject(JSON.parseObject(loginUserInfo), LoginUser.class);
        if (!Optional.ofNullable(loginUser).isPresent()) {
            throw new RuntimeException("用户异常");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}